package org.kele.sc2020.consumer.mqlistener;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.SmartLifecycle;
import org.springframework.stereotype.Component;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static org.kele.sc2020.consumer.controller.ConsumController.BLOCKING_QUEUE;

@Slf4j
@Component
public class BizInternalQueueListener implements SmartLifecycle {

    private volatile boolean running;

    private ExecutorService executorService;

    @Override
    public synchronized void start() {
        executorService = Executors.newSingleThreadExecutor();
        this.running = true;
        comsumFromQueue();
        log.info("启动内部队列监听...");
    }

    @Override
    public synchronized void stop() {
        this.running = false;
        executorService.shutdown();
        log.info("关闭内部队列监听...");
    }

    @Override
    public boolean isRunning() {
        return running;
    }

    public void comsumFromQueue() {
        executorService.execute(() -> {
            while (isRunning()) {
                mainLoop();
            }
        });
    }

    private void mainLoop() {
        Object poll = BLOCKING_QUEUE.poll();
        if (poll != null) {
            System.out.println("消费元素:" + poll);
        }
        try {
            TimeUnit.MICROSECONDS.sleep(1L);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
}
